package com.cooper.controllers;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.constants.DisTypeConstants;
import com.cooper.constants.ResourceConstants;
import com.cooper.core.MinasPropertyHandler;
import com.cooper.entity.BrandBaseEntity;
import com.cooper.entity.DesignerEntity;
import com.cooper.entity.DisplayPicConfigListDo;
import com.cooper.pagination.PageInfo;
import com.cooper.pagination.PageResult;
import com.cooper.service.admin.DisplayPicConfigService;
import com.cooper.service.item.ItemInfoService;
import com.cooper.service.seller.DesignerService;
import com.cooper.vo.CompositeHotShopItemsVo;
import com.cooper.vo.DesignerVo;
import com.cooper.vo.DisplayPicConfigVo;
import com.cooper.vo.ItemInfoVo;
import com.cooper.vo.ItemSearchVo;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.portal.Portal;

@Path("")
public class HomeController {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private DisplayPicConfigService displayPicConfigService;
	
	@Autowired
	private DesignerService designerService;
	
	@Autowired
	private ItemInfoService itemInfoService;
	
	@Autowired
	private MinasPropertyHandler minasPropertyHandler;
	
	@Get
	public String execute(Invocation inv) {
//		String sessionInvitationCode = (String)inv.getRequest().getSession().getAttribute("invitationCode");
//		Cookie[] cookies = inv.getRequest().getCookies();
//		String cookieInvitationCode = "";
//		if(null != cookies && 0 < cookies.length){
//			for(Cookie cookie: cookies){
//				if("invitationCode".equals(cookie.getName())){
//					cookieInvitationCode = cookie.getValue();
//				}
//			}
//		}
//		
//		if(StringUtils.isEmpty(sessionInvitationCode) && StringUtils.isEmpty(cookieInvitationCode)){
//			return "r:/invitation";
//		} else {
//			return "r:/default";
//		}
		return "r:/default";
	}
	
	@Get("invalidate")
	public String invalidate(Invocation inv, Portal portal) {
		inv.getRequest().getSession().invalidate();
		return "r:/";
	}
	
	@Get("brandListWindow")
	public Object brandList(Invocation inv,BrandBaseEntity brand){
		StringBuffer buf = new StringBuffer();
		try{
			DisplayPicConfigVo queryParamVo = new DisplayPicConfigVo();
			queryParamVo.setStatus(DisplayPicConfigListDo.DISPLAY_YES);
			queryParamVo.setDisType(DisTypeConstants.INDEX_BRAND);
			PageInfo pageInfo = new PageInfo();
			pageInfo.setPageIndex(1);
			pageInfo.setPageSize(6);
			PageResult<DisplayPicConfigVo> ret = this.displayPicConfigService.queryDisplayPicConfigPage(queryParamVo, pageInfo);
			if(ret!=null&&ret.getResult().size()>0){
				for(int i=0;i<ret.getResult().size();i++){
					String styleClass="left";
			    	if((i+1)%3==0){
			    		styleClass = "right";
			    	}
			    	 buf.append("<div class='brandBanner brandBanner"+(i+1)+" "+styleClass+"'><a href='"+ret.getResult().get(i).getPath()+
			    			 "'><img src="+this.minasPropertyHandler.getFileServer()+"download/"+ret.getResult().get(i).getFileId()+" alt=''" + "/></a></div>" );
				}
			}
		}catch(Exception e){
			logger.error("IndexController-brandList-error",e);
		}
		return "@"+buf.toString();
	}
	
	@Get("designerFirstListWindow")
	public Object designerFirstListWindow(Invocation inv){
		StringBuffer buf = new StringBuffer();
		try{
			DisplayPicConfigVo queryParamVo = new DisplayPicConfigVo();
			queryParamVo.setStatus(DisplayPicConfigListDo.DISPLAY_YES);
			queryParamVo.setDisType(DisTypeConstants.INDEX_DESIGNER);
			PageInfo pageInfo = new PageInfo();
			pageInfo.setPageIndex(1);
			pageInfo.setPageSize(6);
			
			PageResult<DisplayPicConfigVo> ret = displayPicConfigService.queryDisplayPicConfigPage(queryParamVo, pageInfo);
			if(ret!=null&&ret.getResult()!=null){
				for(DisplayPicConfigVo item:ret.getResult()){
					 //buf.append("<div>");
					 buf.append("<a href='#' class='item'><img src="+this.minasPropertyHandler.getFileServer()+"download/"+item.getFileId()+" alt=''></a>");
				}
			}
			
		}catch(Exception e){
			logger.error("ProjectController-designerFirstList-error",e);
		}
		return "@"+buf.toString();
	}
	
	@Get("getHotShops")
	public Object getHotShops(Invocation inv, PageInfo pageInfo){
		String str1 = this.getHotShopsByType(inv, pageInfo, ResourceConstants.SellerType.PERSONAL);
		String str2 = this.getHotShopsByType(inv, pageInfo, ResourceConstants.SellerType.INDEPENDENT_BRAND);
		return "@"+(str1+str2);
	}
	
	private String getHotShopsByType(Invocation inv, PageInfo pageInfo,String sellerType){
		StringBuffer buf = new StringBuffer();
		try{
			pageInfo.setPageSize(6);
			PageResult<DesignerVo> ret = designerService.findHotShops(sellerType,pageInfo);
			List<CompositeHotShopItemsVo> dataList = new ArrayList<CompositeHotShopItemsVo>();
            if(ret!=null){
            	for(DesignerVo designer:ret.getResult()){
            		CompositeHotShopItemsVo shop = new CompositeHotShopItemsVo();
            		shop.setDesignerVo(designer);
            		PageInfo itemPageInfo = new PageInfo();
            		itemPageInfo.setPageSize(4);
            		itemPageInfo.setPageIndex(1);
            		itemPageInfo.setRowCount(itemInfoService.queryItemInfoCount(designer.getUserId(), new ItemSearchVo()));
        			List<ItemInfoVo> itemList = itemInfoService.queryItemInfoList(designer.getUserId(), new ItemSearchVo(), itemPageInfo);
            		shop.setItemList(itemList);
            		shop.setItemPageInfo(itemPageInfo);
            		dataList.add(shop);
            	}
            	
            	if(CollectionUtils.isNotEmpty(dataList)){
            		for(int i=0; i< dataList.size();i++){
            			CompositeHotShopItemsVo shop = dataList.get(i);
            			DesignerVo designer = shop.getDesignerVo();
            			String divId = "hotShopUnit"+designer.getUserId();
            			if((i+1)%3==1){
            				buf.append("<div userId='"+designer.getUserId()+"' id='"+divId+"' class='shopUnit left'>");
            			}
            			if((i+1)%3==2){
            				buf.append("<div userId='"+designer.getUserId()+"' id='"+divId+"' class='shopUnit left shopMiddleMargin'>");
            			}
            			if((i+1)%3==0){
            				buf.append("<div userId='"+designer.getUserId()+"' id='"+divId+"' class='shopUnit right'>");
            			}
            			buf.append("<div class='row'>");
            			int itemLen = (null == shop.getItemList())?0: shop.getItemList().size();
            			if(CollectionUtils.isNotEmpty(shop.getItemList())){
            				for(int index=0; index < itemLen; index++){
            					ItemInfoVo itemVo = shop.getItemList().get(index);
            					buf.append("<a target='_blank' href='item/detail?id="+itemVo.getId()+"'>");
            					String fileId = itemVo.getMainUrl().replaceAll("download/", "");
            					buf.append("<img class='shopImage "+((index+1)%2==1?"left":"right")+"' src='"+this.minasPropertyHandler.getFileServer()+"image/resize/"+fileId+"?width=180&height=180"+"'/>");
            					buf.append("</a>");
            				}
            			}
            			for(int index=itemLen; index < 4; index++){
            				buf.append("<img class='shopImage "+((index+1)%2==1?"left":"right")+"' src='static/images/global/blank.png'/>");
            			}
            			buf.append("</div>");
						buf.append("<div class='shopName font en_LM fontColorGray left'>"+designer.getStoreName().toUpperCase()+"&nbsp;&nbsp;的店</div>");
						buf.append("<div class='row'>");
						buf.append("<div class='shopReview font en_M fontColorGray left' onclick='shopFavorite(this,\""+designer.getUserId()+"\")'><span class='ReviewCount left'>"+dataList.get(i).getItemPageInfo().getRowCount()+"</span><p class='left'>LIKE</p></div>");	 
						buf.append("<div class='shopUnitSwitch right'  onclick=\"fetchNextItems('"+divId+"',"+(shop.getItemPageInfo().getPageIndex()+1)+")\"></div>");
						buf.append("</div>");
						buf.append("<a target='_blank' class='salerPhoto relative' href='seller/sellerHome?sellerId="+dataList.get(i).getDesignerVo().getUserId()+"'><img src='"+this.minasPropertyHandler.getFileServer()+"image/resize/"+dataList.get(i).getDesignerVo().getSellerFileId()+"?width=80&height=80'/></a>");
						buf.append("</div>");
            		}
            	}
            }
		}catch(Exception e){
			logger.error("ProjectController-getPersonalHotShops-error",e);
		}
		return buf.toString();
	}
	
	
	@Post("getHotShopNextItems")
	public Object getHotShopNextItems(Invocation inv,@Param("userId") Long sellerId, @Param("divId") String divId, PageInfo pageInfo){
		StringBuffer buf = new StringBuffer();
		try{
			DesignerEntity designer = designerService.findDesignerByUserId(sellerId);
			pageInfo.setPageSize(4);
			pageInfo.setRowCount(itemInfoService.queryItemInfoCount(designer.getUserId(), new ItemSearchVo()));
			if(pageInfo.getPageIndex() > pageInfo.getTotalPage()){
				pageInfo.setPageIndex(1);
			}
			List<ItemInfoVo> itemList = itemInfoService.queryItemInfoList(designer.getUserId(),new ItemSearchVo() , pageInfo);
			buf.append("<div class='row'>");
			int itemLen = (null == itemList)?0: itemList.size();
			if(CollectionUtils.isNotEmpty(itemList)){
				for(int index=0; index < itemLen; index++){
					ItemInfoVo itemVo = itemList.get(index);
					buf.append("<a target='_blank' href='item/detail?id="+itemVo.getId()+"'>");
					String fileId = itemVo.getMainUrl().replaceAll("download/", "");
					buf.append("<img class='shopImage "+((index+1)%2==1?"left":"right")+"' src='"+
							this.minasPropertyHandler.getFileServer()+"image/resize/"+fileId+"?width=180&height=180"+"'/>");
					buf.append("</a>");
				}
			}
			for(int index=itemLen; index < 4; index++){
				buf.append("<img class='shopImage "+((index+1)%2==1?"left":"right")+"' src='static/images/global/blank.png'/>");
			}
			buf.append("</div>");
		     buf.append("<div class='shopName font en_LM fontColorGray left'>"+designer.getStoreName()+"</div>");
		     buf.append("<div class='row'>");
		     buf.append("<div class='shopReview font en_M fontColorGray left' onclick='shopFavorite(this,\""+designer.getUserId()+"\")'><span class='ReviewCount left'>"+pageInfo.getRowCount()+"</span><p class='left'>LIKE</p></div>");	 
		     buf.append("<div class='shopUnitSwitch right'  onclick=\"fetchNextItems('"+divId+"',"+(pageInfo.getPageIndex()+1)+")\"></div>");
		     buf.append("</div>");
		     buf.append("<<a target='_blank' class='salerPhoto relative' href='seller/sellerHome?sellerId="+designer.getUserId()+"'><img src='"+
		    		 this.minasPropertyHandler.getFileServer()+"image/resize/"+designer.getSellerFileId()+"?width=80&height=80'/></a>");
            	
		}catch(Exception e){
			logger.error("ProjectController-getHotShops-error",e);
		}
		
		return "@"+buf.toString();
	}
	
}
